<template>
  <div class="join-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入关联ID"
          clearable
          @keyup.enter="handleQuery"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="学号" prop="studentId">
        <el-input
          v-model="queryParams.studentId"
          placeholder="请输入学号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 130px"
        />
      </el-form-item>

      <!-- <el-form-item label="课程ID" prop="courseId">
        <el-input
          v-model="queryParams.courseId"
          placeholder="请输入课程ID"
          clearable
          @keyup.enter="handleQuery"
          style="width: 130px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:join:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:join:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:join:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:join:export']"
        >导出</el-button>
      </el-col>
      
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="joinList" @selection-change="handleSelectionChange" :key="tableKey">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="关联ID" align="center" prop="id" />
      <el-table-column label="姓名" align="center" prop="studentName" />
      <el-table-column label="学号" align="center" prop="studentId" />
      <el-table-column label="课程ID" align="center" prop="courseId" />
      <el-table-column label="状态" align="center" prop="isJoined" >
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.isJoined)" :key="scope.row.id + '-' + scope.row.isJoined">
            {{ getStatusText(scope.row.isJoined) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="加入日期" align="center" prop="joinDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.joinDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="删除标志" align="center" prop="delFlag" />
      <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:join:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:join:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程学生关联对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="joinRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学号" />
        </el-form-item>
        <!-- <el-form-item label="课程ID" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入课程ID" />
        </el-form-item> -->
        <el-form-item label="状态" prop="isJoined">
          <el-radio-group v-model="form.isJoined">
            <el-radio :label="0">未加入</el-radio>
            <el-radio :label="1">已加入</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, getCurrentInstance, toRefs } from 'vue';
import { listCourse, getCourse, delCourse, addCourse, updateCourse } from "@/api/coursemanagement/join";
import { parseTime } from "@/utils/ruoyi";
const { proxy } = getCurrentInstance();






// 定义组件属性
const props = defineProps({
  courseId: {
    type: String,
    required: true
  }
});

const joinList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const tableKey = ref(0); // 用于强制刷新表格



const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    studentId: null,
    courseId: props.courseId || null,
    status: null,
    isJoined: null,
    joinDate: null,
  },
  rules: {
    studentName: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    studentId: [
      { required: true, message: "学号不能为空", trigger: "blur" }
    ],
    isJoined: [
      { required: true, message: "状态不能为空", trigger: "blur" }
    ],
    joinDate: [
      { required: true, message: "加入日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 计算属性来处理状态显示
const getStatusType = (status) => {
  // 处理不同数据类型
  const numericStatus = typeof status === 'string' ? parseInt(status, 10) : status;
  return numericStatus === 1 ? 'success' : 'info';
};

const getStatusText = (status) => {
  // 处理不同数据类型
  const numericStatus = typeof status === 'string' ? parseInt(status, 10) : status;
  return numericStatus === 1 ? '已加入' : '未加入';
};

/** 查询课程学生关联列表 */
function getList() {
  loading.value = true;
  // 设置查询参数中的课程ID
  queryParams.value.courseId = props.courseId;
  listCourse(queryParams.value).then(response => {
    if (response.rows) {
      // 确保 isJoined 是数字类型
      response.rows = response.rows.map(item => {
        if (typeof item.isJoined === 'string') {
          item.isJoined = parseInt(item.isJoined, 10);
        }
        return item;
      });
    }
    joinList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    // 强制刷新表格以确保状态更新
    tableKey.value += 1;
  }).catch(error => {
    console.error('获取列表失败:', error);
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    studentName: null,
    studentId: null,
    courseId: props.courseId,
    status: null,
    isJoined: 1, // 默认已加入
    joinDate: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("joinRef");
  // 确保 isJoined 是数字类型
  form.value.isJoined = Number(form.value.isJoined);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加课程学生关联";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCourse(_id).then(response => {
    form.value = response.data;
    // 确保 isJoined 字段正确回显并处理数据类型
    if (response.data.isJoined !== undefined) {
      form.value.isJoined = typeof response.data.isJoined === 'string' ? 
        parseInt(response.data.isJoined, 10) : 
        Number(response.data.isJoined);
    }
    open.value = true;
    title.value = "修改课程学生关联";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["joinRef"].validate(valid => {
    if (valid) {
      proxy.$modal.loading("正在提交中...");
      // 确保提交前 isJoined 是数字类型
      const submitData = { ...form.value };
      submitData.isJoined = typeof submitData.isJoined === 'string' ? 
        parseInt(submitData.isJoined, 10) : 
        Number(submitData.isJoined);
      
      if (submitData.id != null) {
        updateCourse(submitData).then(response => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          // 立即刷新列表以确保状态更新
          getList();
        }).catch(error => {
          proxy.$modal.closeLoading();
          console.error('修改失败:', error);
        });
      } else {
        addCourse(submitData).then(response => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(error => {
          proxy.$modal.closeLoading();
          console.error('新增失败:', error);
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除课程学生关联编号为"' + _ids + '"的数据项？').then(function() {
    return delCourse(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/join/export', {
    ...queryParams.value
  }, `join_${new Date().getTime()}.xlsx`)
}

// 监听 courseId 的变化，当变化时执行 getList()
watch(() => props.courseId, () => {
  queryParams.value.courseId = props.courseId;
  getList();
});

// 监听表单数据变化，确保 isJoined 字段响应性
watch(() => form.value, (newVal) => {
  if (newVal && newVal.isJoined !== undefined) {
    // 确保 isJoined 字段保持响应性
    form.value.isJoined = Number(newVal.isJoined);
  }
}, { deep: true });

onMounted(() => {
  getList();
});
</script>

<style scoped>
.join-container {
  padding: 20px;
}
</style>